<template>
  <div>
    <el-dialog
      title="图片剪裁"
      :visible.sync="dialogVisiblex"
      :close-on-press-escape="true"
      :close-on-click-modal="false"
      append-to-body
      width="1000px"
      @open="openBtn"
      @close="closeBtn"
    >
      <div class="row">
        <div>
          <div class="preview-box">
            <!-- 2.一个用于给Cropper.js覆盖使用的img  -->
            <img :id="cropImg" class="cropImg" />
          </div>
        </div>
      </div>
      <div class="col-md-3">
        <form class="btn-box">
          <div class="form-group">
            <el-button class="btn btn-success btn-block" @click="closeBtn">
              取消
            </el-button>
          </div>
          <div class="form-group">
            <el-button
              type="primary"
              class="btn btn-success btn-block"
              @click="GetData()"
            >
              确认
            </el-button>
          </div>
        </form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
//引入Cropper.js
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
let CROPPER //创建一个cropper的全局对象
export default {
  components: {},
  props: {
    uploadImg: {
      type: String,
      required: true
    },
    cropImg: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      dialogVisiblex: false,
      cutImgSrc: ''
    }
  },
  computed: {},
  mounted() {},
  activated() {},
  methods: {
    openBtn() {},
    // 父组件触发的方法
    showModal(functionName) {
      this.uploadImgimg()
      // console.log(functionName)
      this.dialogVisiblex = true
      setTimeout(() => {
        this.loadingImg(functionName)
      }, 100)
    },

    loadingImg(eve) {
      //读取上传文件
      let reader = new FileReader()
      if (eve.file) {
        //readAsDataURL方法可以将File对象转化为data:URL格式的字符串（base64编码）
        reader.readAsDataURL(eve.file)
        reader.onload = e => {
          let dataURL = reader.result
          //将img的src改为刚上传的文件的转换格式
          document.querySelector('#' + this.cropImg).src = dataURL

          const image = document.getElementById(this.cropImg)
          console.log(image)
          //创建cropper实例-----------------------------------------
          CROPPER = new Cropper(image, {
            aspectRatio: eve.cutWidth / eve.cutHeight,
            viewMode: 0,
            minContainerWidth: eve.cutWidth,
            minContainerHeight: eve.cutHeight,
            dragMode: 'move',
            preview: []
            // preview: [document.querySelector('.previewBox')]
          })
        }
      }
    },
    // 点击确认
    GetData() {
      //getCroppedCanvas方法可以将裁剪区域的数据转换成canvas数据
      //然后调用浏览器原生的toDataURL方法将canvas数据转换成base64数据
      const imgData = CROPPER.getCroppedCanvas({
        maxWidth: 4096,
        maxHeight: 4096,
        fillColor: '#fff',
        imageSmoothingEnabled: true,
        imageSmoothingQuality: 'high'
      }).toDataURL('image/jpeg', 0.95)
      this.getFileFromBase64(imgData)
    },
    getFileFromBase64(data) {
      let _fileObj = null // File对象
      let fileName = '图片1.png' // 文件名
      let opType = data.split(';base64')[0].slice(5)
      const dataArr = data.split(',')
      const byteString = atob(dataArr[1])
      const options = {
        type: opType,
        endings: 'native'
      }
      const u8Arr = new Uint8Array(byteString.length)
      for (let i = 0; i < byteString.length; i++) {
        u8Arr[i] = byteString.charCodeAt(i)
      }
      _fileObj = new File([u8Arr], fileName, options)
      let imgList = {
        dataURL: data,
        file: _fileObj
      }
      this.$emit('cropPicture', imgList)
      this.dialogVisiblex = false
      this.uploadImgimg()
    },

    // 重复上传的问题
    uploadImgimg() {
      if (CROPPER) {
        CROPPER.destroy()
      }
    },
    // 点击取消
    closeBtn() {
      this.dialogVisiblex = false
      this.uploadImgimg()
    }
  }
}
</script>
<style lang="scss">
.btn-box {
  display: flex;
  position: absolute;
  right: 33px;
  justify-content: space-around;
  padding-top: 20px;
}
.form-group {
  margin-left: 20px;
}
.inpuFile {
  display: none;
}
// .previewBox{
//   box-shadow: 0 0 5px #adadad;
//   width: 345px;
//   height: 150px;
//   margin-top: 30px;
//   overflow: hidden;       /*这个超出设置为隐藏很重要，否则就会整个显示出来了*/
// }
.cropImg {
  height: 150px;
  width: 345px;
  box-shadow: 0 0 5px #adadad;
}
.preview-box {
  margin: auto;
  width: 950px;
  height: 500px;
  overflow: hidden;
}
.col-md-3 {
  height: 40px;
}
</style>
